package org.artifact.xls.convert.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriteConfig;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

public class CsvFileConvert extends AbstractFileConvert {



    // CSV配置
    static CsvWriteConfig CSV_WRITE_CONFIG = new CsvWriteConfig();
    static {
        CSV_WRITE_CONFIG.setFieldSeparator(';');
    }

    @Override
    public void onConvertXlsx(String fileName,ExcelReader reader, String outputPath) {
        File outputFile = FileUtil.newFile(outputPath + File.separator + getDir() + File.separator + fileName + ".csv");

        CsvWriter writer = CsvUtil.getWriter(outputFile, CharsetUtil.CHARSET_UTF_8, false, CSV_WRITE_CONFIG);
        List<Object> types = reader.readRow(1);
        List<List<Object>> rows = reader.read();

        List<Object> tags = rows.get(3);
        int column = tags.size();
        for (int i = 0; i < column; i++) {
            if (tags.get(i) ==null){
                column--;
                continue;
            }else {
                String tag = tags.get(i).toString();
                if (StrUtil.contains(tag, "n") || StrUtil.isEmpty(tag)) {
                    column--;
                }
            }
        }
        int row = 0;

		for (List<Object> list : rows) {
            row++;
			String[] array = new String[column];
            int ignore = 0;
			for (int i = 0; i < list.size(); i++) {
			    // 不需要的列
                if (i > tags.size()-1 || tags.get(i) == null){
                    ignore++;
                    continue;
                }else {
                    String tag = tags.get(i).toString();
                    if (StrUtil.contains(tag, "n")|| StrUtil.isEmpty(tag)) {
                        ignore++;
                        continue;
                    }
                }
                String content = list.get(i) == null ? "" : list.get(i).toString();
			    if (row > 4){
                    String type = types.get(i).toString();
                    switch (type){
                        case TYPE_TXT:
                            String md5 = SecureUtil.md5(content);
                            i18n.put(md5, content);
                            content = md5;
                            break;
                        case TYPE_INT:
                        case TYPE_INT_ARRAY:
                            content = StrUtil.subBefore(content,".",false);
                            break;
                        default:
                            break;
                    }
                }

				array[i-ignore] = content.replace("，",",");
			}
			writer.write(array);
		}
    }

    @Override
    public void convertYml(File file, String outputPath) {
        // 服务器沿用yml
        String fileName = FileUtil.mainName(file);
        File outputFile = FileUtil.newFile(outputPath + File.separator + getDir() + File.separator + fileName + ".yml");
        FileUtil.copy(file,outputFile,true);


        // 生成客户端用的json
        Yaml yaml = new Yaml();
        Map result = null;
        try {
            result = (Map) yaml.load(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String json = JSONUtil.toJsonStr(result);
        String formatJson = JSONUtil.formatJsonStr(json);
        outputFile = FileUtil.newFile(outputPath + File.separator + getDir() + File.separator + fileName + ".json");
        FileUtil.writeUtf8String(formatJson, outputFile);

        //
        outputFile = FileUtil.newFile(outputPath + File.separator + getDir() + File.separator + fileName + ".csv");
        FileUtil.writeUtf8String(formatJson, outputFile);
    }

    @Override
    public String getDir() {
        return "csv";
    }

    @Override
    public void writeI18nFile(String outputPath) {
        File outputFile = FileUtil.newFile(outputPath + File.separator + getDir() + File.separator + "I18n.csv");
        CsvWriter writer = CsvUtil.getWriter(outputFile, CharsetUtil.CHARSET_UTF_8, false, CSV_WRITE_CONFIG);
        String[][] head = new String[][]{
                new String[]{ "id","val"},
                new String[]{ "str","str"},
                new String[]{ "主键","文字"},
                new String[]{ "c|s","c|s"}
        };
        for (String[] array : head) {
            writer.write(array);
        }


        for (Map.Entry<String, String> e : i18n.entrySet()) {
            String[] array = new String[2];
            array[0] = e.getKey();
            array[1] = e.getValue();
            writer.write(array);
        }
    }
}
